let xmlparser = require( 'express-xml-bodyparser' );
let bodyParser = require('body-parser');
let MongoClient = require( 'mongodb' ).MongoClient;
let router = require( './router' );
let startRealTime = require( './init/startRealTime' );
let packageRoute = require( './init/packageRoute' );
let { partyM, intentM, userInfoM, momentsM } = require( './db/index' );
let app = require( 'express' )();
let server = require('http').Server(app);
let io = require('socket.io')(server);


app.use( bodyParser.json());
app.use( xmlparser() );



const connectToDb = () => {
  let url = 'mongodb://47.97.6.69:27017';

  return MongoClient.connect( url, {
    auth: {
      user: 'zhaozhao',
      password: 'zhao!123'
    }
  } ).then( client => {
    return new Promise( ( resolve, reject ) => {
      let db = client.db('party');
      if ( !db ) reject( '选择数据库 "party" 发生错误' );

      // 将之后要到的数据库实体保存到全局
      // party 数据库
      partyM.set( db );

      // order 订单集
      intentM.set( db.collection('intent') );

      // order 用户信息集
      userInfoM.set( db.collection('userInfo') );

      // 动态集
      momentsM.set( db.collection('moments') );




      resolve();
    });
  } );
};


const listen3000 = () => {
  server.listen( 3000, '47.97.6.69', function () {
    console.log( '开始监听 3000 ty.axuuh.cn' );
  } );
};




// 拼装路由
packageRoute( app, router );

// 开启赏金池展示实时展示页面功能
startRealTime(io);

// 连接数据库
connectToDb()

  // 监听3000 端口
  .then( listen3000 )

  .catch( console.error );


